// Created by 11372 on 2021/12/24 15:58
#include <iostream>
#include <vector>
#include <queue>

using namespace std;

/**
 * 执行用时：204 ms, 在所有 C++ 提交中击败了17.27%的用户
 * 内存消耗：45.8 MB, 在所有 C++ 提交中击败了98.18%的用户
 */
#define x first
#define y second

typedef pair<int, int> PII;  // (截止日期，苹果数目）

class Solution {
public:
    int eatenApples(vector<int> &apples, vector<int> &days) {

        int n = apples.size();
        priority_queue<PII, vector<PII>, greater<PII>> heap;
        int t = 0, res = 0;
        while (t < n || heap.size()) {
            if (t < n && apples[t]) heap.push({t + days[t] - 1, apples[t]});  // t + days[t] - 1 天还可以吃，下一天就不能吃了
            while (heap.size() && heap.top().x < t) heap.pop();  // 过期了 则删除
            if (heap.size()) {
                res++;
                auto p = heap.top();
                heap.pop();
                if (p.y > 1) heap.push({p.x, p.y - 1});
            }
            t++;
        }
        return res;
    }
};

int main() {

    vector<int> apples = {1, 2, 3, 5, 2}, days = {3, 2, 1, 4, 2};
    cout << Solution().eatenApples(apples, days) << endl;  // 7

    return 0;
}
